package com.cf.docker.service;

import com.cf.constant.EnumReturnCode;
import com.cf.crud.service.AbsBaseService;
import com.cf.docker.dao.ContainerDao;
import com.cf.docker.model.Container;
import com.cf.docker.model.Machine;
import com.cf.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * boot-awm-ContainerService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/20 下午 02:49
 */
public class ContainerService extends AbsBaseService<Container, ContainerDao> {

    @Autowired
    private DockerService dockerService;

    @Override
    public Container insert(Container bean) {
        String containerId = dockerService.createDockerContainer(bean.getImgId(), bean.getCmdParameter());
        if (StringUtils.isEmpty(containerId)) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "创建镜像失败！");
        }
        bean.setContainerId(containerId);
        Container insertContainer = super.insert(bean);
        return insertContainer;
    }

    public boolean startContainer(long containerId) {
        Container container = this.selectOne(containerId);
        dockerService.runDockerContainer(container.getImgId(), container.getContainerId());
        container.setRunState(true);
        this.update(container);
        return true;
    }

    @Override
    public Integer deleteById(long id) {
        Container container = selectOne(id);
        if (container == null)
            return 0;
        dockerService.stopContainer(container.getMachineId(), container.getContainerId());
        Integer integer = super.deleteById(id);
        return integer;
    }

    @Override
    public Class getTargetClass() {
        return Container.class;
    }

}
